package cn.mymall.support;

import org.springframework.beans.MutablePropertyValues;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class RequestMapPropertyValues extends MutablePropertyValues {
	private static final long serialVersionUID = -6960200050075948829L;
	public static final String DEFAULT_PREFIX_SEPARATOR = "_";
	public RequestMapPropertyValues(Map requestParams) {
		this(requestParams, null, null);
	}


	public RequestMapPropertyValues(Map<String, Object> requestParams, String prefix) {
		this(requestParams, prefix, DEFAULT_PREFIX_SEPARATOR);
	}


	public RequestMapPropertyValues(Map requestParams, String prefix, String prefixSeparator) {
		super(getParametersStartingWith(requestParams, (prefix != null) ? prefix + prefixSeparator : null));
	}
	public static Map<String, Object> getParametersStartingWith(Map requestParams, String prefix) {
		Iterator paramNames = requestParams.keySet().iterator();
		Map params = new TreeMap();
		if (prefix == null) {
			prefix = "";
		}
		while (paramNames != null && paramNames.hasNext()) {
			String paramName = (String) paramNames.next();
			if ("".equals(prefix) || paramName.startsWith(prefix)) {
				String unprefixed = paramName.substring(prefix.length());
				Object values = requestParams.get(paramName);
				if (values == null) {
					// Do nothing, no values found at all.
				}else{
					if(values instanceof String[]){
						if (((String[])values).length > 1) {
							params.put(unprefixed, values);
						}else {
							params.put(unprefixed, ((String[])values)[0]);
						}
					}else{
						params.put(unprefixed, values);
					}
				}
			}
		}
		return params;
	}

}

